const { dictItemFind } = require('../../api/index');

// components/ActionSheet/index.js
Component({
  /*** 组件的属性列表 */
  properties: {
  
  },
  /*** 组件的初始数据 */
  data: {
    finshed: false,
    show: false,
    fieldValue: '',
    cascaderValue: '',
    actions: [],
    formData: {
      pageNumber: 1,
      pageSize: 1000,
      dictName: "XZQH",
      pcode: "000"
    },
    success: function() {},
    error: function() {}
  },

  /*** 组件的方法列表 */
  methods: {
    open(options = {}) {
      const { 
        actions = [], 
        success = () => {}, 
        error = () => {} 
      } = options;

      this.setData({ actions, success, error }, () => {
        this.setData({ show: true })
      }); 
    },
    close() {
      this.setData({ show: false });
    },
    async change(e) {
      wx.showLoading({ title: '加载中...' });
      const { value, selectedOptions } = e.detail;

      if(selectedOptions.length) {
        const curOpt = selectedOptions[ selectedOptions.length - 1 ];

        if(curOpt.leaf) {
          wx.hideLoading();
          this.close();
        } 
      }

      this.data.formData.pcode = value;
      //  动态加载数据 - 将数据添加进去
      let { errors = [], result = [] } = await dictItemFind(this.data.formData);
      if(errors.length > 0) { return; }

      //  找到当前选中的元素的下标
      const index = this.data.actions?.findIndex(_s => _s.value === value);

      if(result.length === 0) {
        result = [ JSON.parse(JSON.stringify(this.data.actions[index])) ];
      }

      if(index !== -1) {
        this.data.actions[index].children = result.map( _s => {
          _s.text = _s.name;
          _s.value = _s.code;
          _s.leaf = true;
          return _s;
        });

        this.setData({ actions: JSON.parse(JSON.stringify( this.data.actions )) }, () => {
          wx.hideLoading();
        });
      }
      wx.hideLoading();
    },
    select(event) { // 通过返回值的方式进行返回
      const { selectedOptions} = event.detail;

      const isLeaf = selectedOptions[ selectedOptions.length - 1 ]?.leaf;
      console.log('85', isLeaf);
      const name = setName( selectedOptions );
      const code = setCode( selectedOptions );
      this.data.success({ name, code });

      if(isLeaf) {
        this.close();
      }
    }
  }
})

//  处理 name
function setName(arr = []) {
  let str = '';
  arr.forEach(_s => {
    return str += `${ _s.text || _s.name }/`;
  })

  return str.replace(/\/$/, '');
}

//  处理 code
function setCode(arr = []) {
  return arr.reduce((prev, _s) => {
    prev.push( _s.text || _s.name );
    return prev;
  }, []);
}